<template>
  <a-button
    type="link"
    style="padding: 4px 6px"
    @click="onClick"
    :loading="loading"
    :disabled="hasEditing && !editing"
  >
    {{ editing ? '保存' : '编辑' }}
  </a-button>
</template>
<script setup>
import { computed } from 'vue'
import { useVModel } from '@vueuse/core'
import { Form, message as Message } from 'ant-design-vue'
import {
  useDataSourceManager,
  useDataSource,
  useParentId,
} from './provide-context.js'
import { createTag, updateTag, createTagGroup } from '@/api/tag.js'
/**
 * 外部参数
 */
let props = defineProps({
  editing: { type: Boolean, default: () => false },
  loading: { type: Boolean, default: () => false },
  data: { type: Object, required: true },
  rules: { type: Object, default: () => ({}) },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:editing', 'update:loading', 'submit'])
/**
 * 双向绑定
 */
let editing = useVModel(props, 'editing', emit)
let loading = useVModel(props, 'loading', emit)
/**
 * 全局
 */
let { update } = useDataSourceManager()
let dataSource = useDataSource()
let parentId = useParentId()
/**
 * 校验相关
 */
let useForm = Form.useForm
let { validate } = useForm(props.data, props.rules)
// 递归检查是否有 editing 为 true 的元素
const checkEditing = items => {
  return items.some(item => {
    if (item.editing === true) {
      return true
    }
    if (item.children && item.children.length > 0) {
      return checkEditing(item.children)
    }
    return false
  })
}
/**
 * 整体有没有在编辑状态
 */
let hasEditing = computed(() => checkEditing(dataSource.value))

/**
 * 操作事件
 */
async function onClick() {
  if (editing.value) {
    loading.value = true
    try {
      emit('submit')
      await validate()
      if (props?.data?.new) {
        if (props?.data?.parentId) {
          await createTag({
            parentId: parentId.value,
            tagName: props.data.tagName,
          })
        } else {
          await createTagGroup({
            tagName: props.data.tagName,
          })
        }
      } else {
        await updateTag({
          tagId: props.data.tagId,
          tagName: props.data.tagName,
        })
      }
      await update()
      editing.value = false
      Message.success('保存成功!')
    } catch (e) {
      Message.error('发布失败!')
    }
    loading.value = false
  } else {
    editing.value = true
  }
}
</script>
